﻿using System;
using IO = System.IO;

namespace YAMM.Tools
{
    public static class Directory
    {
        /// <summary>
        /// Copies the specified source directory.
        /// </summary>
        /// <param name="sourceDirectory">The source directory.</param>
        /// <param name="targetDirectory">The target directory.</param>
        public static void Copy(string sourceDirectory, string targetDirectory)
        {
            CopyRecursive(new IO.DirectoryInfo(sourceDirectory), new IO.DirectoryInfo(targetDirectory));
        }

        /// <summary>
        /// Copies the specified source directory.
        /// </summary>
        /// <param name="sourceDirectory">The source directory.</param>
        /// <param name="targetDirectory">The target directory.</param>
        public static void Copy(IO.DirectoryInfo sourceDirectory, IO.DirectoryInfo targetDirectory)
        {
            CopyRecursive(sourceDirectory, targetDirectory);
        }

        /// <summary>
        /// Copies a directory recursive.
        /// </summary>
        /// <param name="source">The source directory.</param>
        /// <param name="target">The target directory.</param>
        private static void CopyRecursive(IO.DirectoryInfo source, IO.DirectoryInfo target)
        {
            // check if the target exists
            if (IO.Directory.Exists(target.FullName) == false)            
                IO.Directory.CreateDirectory(target.FullName);
            
            // copy all files
            foreach (IO.FileInfo fInfo in source.GetFiles())
            {
                fInfo.CopyTo(IO.Path.Combine(target.ToString(), fInfo.Name), true);
            }

            // copy all subdirectory
            foreach (IO.DirectoryInfo dInfoSubDir in source.GetDirectories())
            {
                // create subdirectory
                IO.DirectoryInfo dInfoNewSubDir = target.CreateSubdirectory(dInfoSubDir.Name);
                // copy all files and dirs rec
                CopyRecursive(dInfoSubDir, dInfoNewSubDir);
            }
        }
    }
}
